package seller

import (
	"dhfshop/models/seller"
	"time"
	//"github.com/astaxie/beego"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego/validation"
)

// 
type ProfitController struct {
	base.BaseController
}

func (this *ProfitController) List() {
	query,_,fields,order_by,offset,limit,err := this.GetQueryPara()
	if err != nil {
	   this.ServeError(err.Error())
	   return
	}
	l, cnt, err := seller.GetAllProfits(query,fields,order_by,offset,limit)
	if err != nil {
	    this.ServeError(err.Error())
	    return
	} else {
		r := struct {
		    TotalCount   int64     `json:"total_count"`
	        Shop    []*seller.Profit `json:"shop"`
	    }{TotalCount: cnt, Shop: l}
	    this.Data["json"] = r
	}
	this.ServeJSON()
}

func (this *ProfitController) Post() {
	var v seller.Profit
	valid := validation.Validation{}
	this.ParseForm(&v)
	valid.Required(v.PartnerId, "partner_id")
	valid.Required(v.Name, "name")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return	
	}
	shopId, err := seller.AddProfit(&v)
	if err != nil {
       this.ServeError(err.Error())
		return
    }
	rsp := struct {
		ShopId    int64        `json:"shop_id"`
	    Created   time.Time    `json:"created"`
	}{ShopId: shopId, Created:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *ProfitController) Put() {
	v := seller.Profit{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return 
	}
	var updateFields []string
    if err := seller.UpdateProfitById(&v, updateFields...); err != nil{
		this.ServeError(err.Error())
		return
	}
	rsp := struct {
		    PartnerId     int64       `json:"partner_id"`
	        Modified   time.Time   `json:"modified"`
	    }{PartnerId:v.PartnerId, Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *ProfitController) Delete() {
	shopId, _ := this.GetInt("shop_id")
	if err := seller.DeleteProfit(int64(shopId)); err == nil {
		rsp := struct {
		    ShopId     int64       `json:"shop_id"`
	        Modified   time.Time   `json:"modified"`
	    }{ShopId:int64(shopId), Modified:time.Now().UTC()}
	    this.Data["json"] = rsp
	} else {
	    this.ServeError(err.Error())
	    return
	}
	this.ServeJSON()
}


